<?php
require_once 'database.php';
try {
    // 创建用户表（如果不存在）
    $pdo->exec("CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        username TEXT NOT NULL UNIQUE,
        password TEXT NOT NULL,
        school TEXT NOT NULL UNIQUE,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )");

    // 创建教师信息表（如果不存在）
    $pdo->exec("CREATE TABLE IF NOT EXISTS teachers (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    subject TEXT NOT NULL,
    work_time TEXT NOT NULL,
    phone TEXT NOT NULL,
    sex TEXT NOT NULL,
    birthday date NOT NULL,
    school TEXT NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    here_work_time TEXT,
    grade TEXT,
    major TEXT,
    educational TEXT,
    qualifications TEXT,
    master_level TEXT)");

    // 创建培训信息表（如果不存在，内容包括：主办科室	培训主题	培训开始时间	培训结束时间	培训地点	培训人数	培训费用	其他费用	其它说明	培训内容）
    $pdo->exec("CREATE TABLE IF NOT EXISTS trainings (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    department TEXT NOT NULL,
    title TEXT NOT NULL,
    start_time date NOT NULL,
    end_time date NOT NULL,
    location TEXT NOT NULL,
    type TEXT NOT NULL,
    content TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP)");

    // 创建培训费用表（如果不存在）
    $pdo->exec("CREATE TABLE IF NOT EXISTS trainings_cost(
    id INTEGER PRIMARY KEY AUTOINCREMENT, 
    trainings_id INTEGER NOT NULL, 
    school TEXT NOT NULL, 
    cost DOUBLE DEFAULT 0, 
    other_cost DOUBLE DEFAULT 0, 
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP);");

    // 创建培训报名表（如果不存在）
    $pdo->exec("CREATE TABLE IF NOT EXISTS trainings_teachers (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    teacher_id INTEGER NOT NULL,
    teacher_name TEXT NOT NULL,
    teacher_subject TEXT NOT NULL,
    teacher_work_time TEXT NOT NULL,
    teacher_phone TEXT NOT NULL,
    teacher_sex TEXT NOT NULL,
    teacher_birthday date NOT NULL,
    teacher_school TEXT NOT NULL,
    training_id INTEGER NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    teacher_here_work_time TEXT,
    teacher_grade TEXT,
    teacher_major TEXT,
    teacher_educational TEXT,
    teacher_qualifications TEXT,
    teacher_master_level TEXT)");

    // 查询 users 表中是否存在名为 admin 的用户
    if ($pdo->exec("SELECT * FROM users WHERE username = 'admin'") === 0) {
        // 插入测试数据（仅用于演示）
        $stmt = $pdo->prepare('INSERT INTO users (username, password, school) VALUES (?,?,?)');
        $stmt->execute(['admin', password_hash("admin", PASSWORD_DEFAULT), '教育局']);
        echo "创建用户成功！";
    }

    echo '数据库初始化成功！';

} catch (PDOException $e) {
    die('数据库初始化失败: ' . $e->getMessage());
}
?>